package com.channel;

import com.handle.DefaultHandle;
import com.handle.RpcResponseHandle;
import com.message.constant.Host;
import com.protocol.MessageCodecSharable;
import com.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author linyu.dai
 * @project rpc
 * @description rpc channel 控制中心
 * @creat 2022/11/27 21:26:34
 */
@Slf4j
public class ChannelContent {

    private static Map<String, Channel> channelHashMap = new ConcurrentHashMap<>();

    /**
     * 剔除相关服务
     */
    public static void removeChannel(String serverName) {
        Channel remove = channelHashMap.remove(serverName);
        //关闭channel
        remove.close();
    }

    public static void addChannel(String serverName, Host host) {
        //服务注册成功
        channelHashMap.put(serverName, getChannel(serverName, host));
    }

    /**
     * 必须先连接上注册中心 否则返回为null
     * 根据服务名获取 对应的channel
     */
    public static Channel getChannel(String serverName) {
        return channelHashMap.get(serverName);
    }

    public static void init(Map<String, Host> registerInfo) {
        registerInfo.forEach((k,v)-> channelHashMap.put(k,getChannel(k,v)));
    }

    private static Channel getChannel(String serverName,Host host){
        log.info("正在连接 服务{}",serverName);
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Channel channel = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(new MessageCodecSharable());
                            ch.pipeline().addLast(new RpcResponseHandle());
                            ch.pipeline().addLast(new DefaultHandle());
                        }
                    }).connect(host.getAddress(), host.getPort()).sync().channel();
            log.info("success connect server:{},{},{}",serverName,host.getAddress(),host.getPort());
            //监听channel关闭
            channel.closeFuture().addListener(future -> {
                //关闭group线程池 彻底关闭client
                group.shutdownGracefully();
            });
            return channel;
        }catch (Exception e){
            log.error("error connect server:{}",e.getMessage());
        }
        return null;
    }
}
